package com.honey.standard.writer.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.honey.core.compiler.Compilation;
import com.honey.core.compiler.CompilationException;

/**
 * 存储文件
 * 
 * @author Administrator
 * 
 */
public abstract class Storage {
	
	private File source = null;

	private String charset = "UTF-8" ;
	
	boolean checked = false ;
	/**
	 * 使用默认的字符集
	 * @param source
	 */
	public Storage(File source,boolean checked) {
		this(source, null,checked);
	}

	/**
	 * 构造函数
	 * @param source 文件
	 * @param charset 字符集
	 */
	public Storage(File source, String charset,boolean checked) {
		this.checked = checked;
		setSource(source);
		if(charset != null && charset.length() > 0 ){
			this.charset = charset;
		}
	}
	
	/**
	 * 构造函数
	 * @param source 被写入的文件
	 * @param charset 字符集
	 */
	public Storage(String source, String charset,boolean checked) {
		this(new File(source), charset,checked);
	}
	
	/**
	 * @param source
	 */
	protected void setSource(File source) {
		this.source = source;
	}

	/**
	 * 获取存储文件
	 * @return the source
	 */
	public final File getSourceFile() {
		return source;
	}
	
	/**
	 * 写入文件
	 * @param compilation 
	 * @throws IOException
	 * @throws CompilationException 
	 */
	public void write(Compilation compilation) throws IOException, CompilationException{
		if( supportWrite() ){
			OutputStream outputStream = null;
			try{
				byte[] bytes = compilation.compiledContent().toString().getBytes(charset);
				outputStream = new FileOutputStream( source ) ;
				outputStream.write(bytes);
				outputStream.flush();
			}finally{
				if( outputStream != null)
					outputStream.close();
			}
		}
	}
	
	/**
	 * 是否支持写入 true:支持写入文件 false:不支持写入文件
	 * @return
	 */
	public abstract boolean supportWrite();
}
